<script>
import {defineComponent} from 'vue'
import authPage from "@/utils/pages/authPage";
import actApi from "@/utils/api/actApi";
import ActItem from "@/views/act/components/ActItem.vue";
import QNList from "@/views/act/components/QNList.vue";
import {closeToast, showFailToast, showLoadingToast} from "vant";
import authApi from "@/utils/api/authApi";
import userApi from "@/utils/api/userApi";
import {JSEncrypt} from "jsencrypt";

export default defineComponent({
  name: "ApplySta",
  components: {QNList, ActItem},
  created() {
    let actId = this.$route.query.actId
    if(actId){
      this.initAct(actId)
    }else {
      authPage.status(-3).open().replace()
    }
    
  },
  data(){
    return {
      act: null,
      user: null,
      qn: [],
      showQn: false
    }
  },
  methods: {
    async getExcel(){
      //TODO 导出excel
      try {
        showLoadingToast({
          message: '导出中...',
          forbidClick: true,
          duration: 0
        });
        let key = await authApi.getPublicKey()
        let userId = await userApi.getUserId()
        let objStr = JSON.stringify({userId, actId: this.act.actId})
        const encryptor = new JSEncrypt()
        encryptor.setPublicKey(key)  // 放入公钥
        let data = encryptor.encrypt(objStr)
        actApi.excel(data, userId)
        closeToast(true)
      }catch (data){
        showFailToast("导出失败，请稍后重试")
      }finally {
      
      }
    },
    gotoQSta(qId){
      this.$router.push({
        path: '/act/apply/q',
        query: {
          actId: this.act.actId,
          qId
        }
      })
    },
    async initAct(actId){
      let {act,user,qn} = await actApi.getActInfo(actId)
      this.user = user
      this.qn = qn
      this.act = act
    }
  }
})
</script>

<template>
  <div style="margin: 10px" v-if="act===null">
    <van-skeleton title avatar :row="3" />
  </div>
  <div v-else class="apply-sta-container-div">
    <ActItem
      :act="act"
      :user="user"
      />
    <div v-show="qn.length > 0" class="show-qn-button-div">
      <el-button v-if="!showQn" @click="showQn = true">显示问卷</el-button>
      <el-button v-else @click="showQn = false">隐藏问卷</el-button>
      <el-button type="primary" @click="getExcel">导出excel</el-button>
    </div>
    <QNList
        @sta="gotoQSta"
        v-show="showQn"
      :qn="qn"
      show
        sta
      />
    
    <router-view ref="component" v-slot="{ Component }">
      <transition>
        <div>
          <keep-alive>
            <component :is="Component" />
          </keep-alive>
        </div>
      </transition>
    </router-view>
    
  </div>
</template>

<style scoped lang="less">
.apply-sta-container-div {
  display: flex;
  flex-direction: column;
  >.show-qn-button-div{
    margin: 0 10%;
    display: flex;
    flex-direction: row;
    justify-content: center;
  }
}
</style>